package ar.com.ford.it.fullEconomics.view.action;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.facade.CommodityFacade;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp01Part;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp02Commodity;
import ar.com.ford.it.fullEconomics.persistence.dto.Teess01Supplier;
import ar.com.ford.it.fullEconomics.util.FullEconomicsDateUtil;
import ar.com.ford.it.fullEconomics.view.form.PartForm;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.facade.FacadeProvider;
import ar.com.ford.it.webengine.struts.AbstractBaseAction;
import ar.com.ford.it.webengine.struts.FordActionMapping;
import ar.com.ford.it.webengine.websession.WebSession;

public class PartAction extends AbstractBaseAction {

    /**
     * Setea el mensaje de "busqueda sin resultados" cuando la busqueda no trae
     * resultados
     * 
     * @param request
     * Request donde se guarda el mensaje
     */
    private void searchWithNoResults(HttpServletRequest request) {
        ActionMessages am = new ActionMessages();
        MessageResources messageResources = (MessageResources) getResources(request);

        am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                "customMessage", messageResources
                        .getMessage("message.noResults")));
        saveMessages(request, am);
    }

    /**
     * Resetea el formulario y envia a la pagina inicial de Parts
     * 
     */
    public ActionForward initPage(FordActionMapping mapping,
                                  ActionForm actionForm,
                                  HttpServletRequest request,
                                  HttpServletResponse response,
                                  WebSession webSession, ActionMessages msgs,
                                  ActionMessages warns, ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        PartForm form = (PartForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        CommodityFacade facade = (CommodityFacade) FacadeProvider.getFacade(
                request, CommodityFacade.class);
        request.getSession().setAttribute("partClassColl",
                facade.getPartClases());
        try {
            request.getSession().setAttribute("commColl",
                    facade.findCommodities("", "", user.getTeesg01Plant()));
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }

        form.resetForm();
        return mapping.findForward("success");
    }

    /**
     * Resetea los campos para el create/update
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward clearCreateFields(FordActionMapping mapping,
                                           ActionForm actionForm,
                                           HttpServletRequest request,
                                           HttpServletResponse response,
                                           WebSession webSession,
                                           ActionMessages msgs,
                                           ActionMessages warns,
                                           ActionMessages errorMsgs) {
        PartForm form = (PartForm) actionForm;

        form.clearCreateUpdateFields();
        return mapping.findForward("success");
    }

    /**
     * Resetea los campos para el create/update
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward clearFindFields(FordActionMapping mapping,
                                         ActionForm actionForm,
                                         HttpServletRequest request,
                                         HttpServletResponse response,
                                         WebSession webSession,
                                         ActionMessages msgs,
                                         ActionMessages warns,
                                         ActionMessages errorMsgs) {
        PartForm form = (PartForm) actionForm;

        form.clearFindFields();
        return mapping.findForward("success");
    }

    /**
     * Se encarga del manejo de la busqueda de Parts
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward findParts(FordActionMapping mapping,
                                   ActionForm actionForm,
                                   HttpServletRequest request,
                                   HttpServletResponse response,
                                   WebSession webSession, ActionMessages msgs,
                                   ActionMessages warns,
                                   ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();

        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        PartForm form = (PartForm) actionForm;
        CommodityFacade facade = (CommodityFacade) FacadeProvider.getFacade(
                request, CommodityFacade.class);
        Collection<Teesp01Part> res = null;
        try {
            String supplierCode = form.getSupplierCode();
            String supplierClass = form.getSupplierClass();
            Timestamp dateInMin = null;
            Timestamp dateInMax = null;
            Timestamp dateOutMin = null;
            Timestamp dateOutMax = null;
            if (!StringUtils.isBlank(form.getDateInMin())) {
                Calendar calDateInMin = FullEconomicsDateUtil.format(form
                        .getDateInMin());
                dateInMin = new Timestamp(calDateInMin.getTimeInMillis());
            }
            if (!StringUtils.isBlank(form.getDateOutMin())) {
                Calendar calDateOutMin = FullEconomicsDateUtil.format(form
                        .getDateOutMin());
                dateOutMin = new Timestamp(calDateOutMin.getTimeInMillis());
            }
            if (!StringUtils.isBlank(form.getDateInMax())) {
                Calendar calDateInMax = FullEconomicsDateUtil.format(form
                        .getDateInMax());
                dateInMax = new Timestamp(calDateInMax.getTimeInMillis());
            }
            if (!StringUtils.isBlank(form.getDateOutMax())) {
                Calendar calDateOutMax = FullEconomicsDateUtil.format(form
                        .getDateOutMax());
                dateOutMax = new Timestamp(calDateOutMax.getTimeInMillis());
            }
            Teesp01Part findPart = new Teesp01Part();
            findPart.setEesp01PartPrefixCodeC(form.getPrefixFind());
            findPart.setEesp01PartBaseCodeC(form.getBaseFind());
            findPart.setEesp01PartSuffixCodeC(form.getSuffixFind());
            findPart.setEesp01PartClassCodeC(form.getPartClassFind());
            findPart.setEesp01PartInDateY(dateInMin);
            findPart.setEesp01PartOutDateY(dateOutMin);
            findPart.setEesp01PlantCodeC(user.getTeesg01Plant());
            if (StringUtils.isBlank(supplierCode) && supplierClass.equals("-1")) {
                res = facade.findParts(findPart, dateInMax, dateOutMax);
            } else {
                res = facade.findParts(findPart, dateInMax, dateOutMax, form
                        .getSupplierClass(), form.getSupplierCode());
            }
            if (res.isEmpty()) {
                searchWithNoResults(request);
            }
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        if (form.getSection().equalsIgnoreCase("delete")) {
            form.setConfirmCascadeDelete((String) request
                    .getAttribute("confirmCascadeDelete"));
            form.setShowConfirmCascadeDelete((String) request
                    .getAttribute("showConfirmCascadeDelete"));
            form.setPartSelected((Teesp01Part) request
                    .getAttribute("partToDelete"));
        }
        form.setParts(res);
        form.clearCreateUpdateFields();
        return mapping.findForward("success");
    }

    /**
     * Setea los campos de edicion de Parts con los valores del Part
     * seleccionado mediante el listado
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward editPart(FordActionMapping mapping,
                                  ActionForm actionForm,
                                  HttpServletRequest request,
                                  HttpServletResponse response,
                                  WebSession webSession, ActionMessages msgs,
                                  ActionMessages warns, ActionMessages errorMsgs) {
        PartForm form = (PartForm) actionForm;
        ActionMessages am = new ActionMessages();
        CommodityFacade facade = (CommodityFacade) FacadeProvider.getFacade(
                request, CommodityFacade.class);
        form.setEditMapped(form.getSelectedRowNum(), "");
        Teesp02Commodity partsCommodity = null;
        try {
            partsCommodity = facade.getPartsEffectiveCommodity(form
                    .getPartSelected());
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        if (partsCommodity != null)
            form.setPartCommodity(partsCommodity.getEesp02CommodityNumberK()
                    .toString());
        else
            form.setPartCommodity("-1");
        form.setPartForEdit(form.getPartSelected());
        return mapping.findForward("success");
    }

    /**
     * En caso de que se haya seleccionado algun Part del listado, entonces lo
     * actualiza, sino llama al metodo encargado de crear el Part
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward createUpdatePart(FordActionMapping mapping,
                                          ActionForm actionForm,
                                          HttpServletRequest request,
                                          HttpServletResponse response,
                                          WebSession webSession,
                                          ActionMessages msgs,
                                          ActionMessages warns,
                                          ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();

        PartForm form = (PartForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        CommodityFacade facade = (CommodityFacade) FacadeProvider.getFacade(
                request, CommodityFacade.class);

        try {
            if (form.getEditBlocked().equalsIgnoreCase("false")) {
                Teesp01Part newPart = form.getPartForCreate();
                newPart.setEesp01PlantCodeC(user.getTeesg01Plant());
                Teesp01Part part = facade.findPartByPk(newPart);
                if (part == null) {
                    facade.createPart(newPart, user);
                    if (!form.getPartCommodity().equalsIgnoreCase("-1"))
                        facade.createCommPart(form.getPartCommodity(), newPart,
                                user);
                } else {
                    am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                            "part.error.existingName"));
                    saveErrors(request, am);
                }
            } else {
                Teesp01Part part = form
                        .getPartForUpdate(form.getPartSelected());
                Teesp02Commodity effCommodity = facade
                        .getPartsEffectiveCommodity(part);
                part.setEesp01PlantCodeC(user.getTeesg01Plant());
                facade.updatePart(part, user);
                if (effCommodity == null) {
                    if (!form.getPartCommodity().equalsIgnoreCase("-1"))
                        facade.createCommPart(form.getPartCommodity(), part,
                                user);
                } else if (Integer.parseInt(form.getPartCommodity()) != effCommodity
                        .getEesp02CommodityNumberK()) {
                    if (!form.getPartCommodity().equalsIgnoreCase("-1"))
                        facade.createCommPart(form.getPartCommodity(), part,
                                user);
                    else
                        facade.closeCommPart(effCommodity, part, user);
                }
            }
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * Elimina el Part seleccionado, verificando que no tenga elementos
     * relacionados
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward deletePart(FordActionMapping mapping,
                                    ActionForm actionForm,
                                    HttpServletRequest request,
                                    HttpServletResponse response,
                                    WebSession webSession, ActionMessages msgs,
                                    ActionMessages warns,
                                    ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();

        PartForm form = (PartForm) actionForm;
        CommodityFacade facade = (CommodityFacade) FacadeProvider.getFacade(
                request, CommodityFacade.class);
        form.setDeleteMapped(form.getSelectedRowNum(), "");
        try {
            if (facade.isDeleteable(form.getPartSelected())) {
                facade.deletePart(form.getPartSelected());
            } else if (form.getConfirmCascadeDelete().equalsIgnoreCase("true")) {
                facade.cascadeDelete(form.getPartSelected());
                request.setAttribute("showConfirmCascadeDelete", "false");
                request.setAttribute("confirmCascadeDelete", "false");
                request.setAttribute("partToDelete", form.getPartSelected());
            } else {
                request.setAttribute("showConfirmCascadeDelete", "true");
            }
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /***************************************************************************
     * Conexion con otras pantallas
     **************************************************************************/
    /**
     * Conexion que permite la conexion hacia la pantalla de Supply con los
     * datos cargados para realizar la busqueda
     */
    public ActionForward goSupplyByPart(FordActionMapping mapping,
                                        ActionForm actionForm,
                                        HttpServletRequest request,
                                        HttpServletResponse response,
                                        WebSession webSession,
                                        ActionMessages msgs,
                                        ActionMessages warns,
                                        ActionMessages errorMsgs) {
        PartForm form = (PartForm) actionForm;
        form.setSeleccMapped(form.getSelectedRowNum(), "");
        request.setAttribute("partFind", form.getPartSelected());
        return mapping.findForward("success");
    }

    public ActionForward goFindBySupplier(FordActionMapping mapping,
                                          ActionForm actionForm,
                                          HttpServletRequest request,
                                          HttpServletResponse response,
                                          WebSession webSession,
                                          ActionMessages msgs,
                                          ActionMessages warns,
                                          ActionMessages errorMsgs) {
        PartForm form = (PartForm) actionForm;
        form.resetForm();
        ActionMessages am = new ActionMessages();
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        CommodityFacade facade = (CommodityFacade) FacadeProvider.getFacade(
                request, CommodityFacade.class);
        request.getSession().setAttribute("partClassColl",
                facade.getPartClases());
        try {
            request.getSession().setAttribute("commColl",
                    facade.findCommodities("", "", user.getTeesg01Plant()));
            Teess01Supplier supplierFind = (Teess01Supplier) request
                    .getAttribute("supplierFind");
            form.setSupplierClass(supplierFind.getEess01SupplierClassCodeC());
            form.setSupplierCode(supplierFind.getEess01SupplierCodeC());
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }
}
